from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from.models import Experience
from.forms import ExperienceForm
from django.contrib import messages


# 经验分享列表视图
def experience_list(request):
    experiences = Experience.objects.all()
    return render(request, 'experiences/experience_list.html', {'experiences': experiences})


# 经验分享详情视图
def experience_detail(request, experience_id):
    experience = get_object_or_404(Experience, id=experience_id)
    return render(request, 'experiences/experience_detail.html', {'experience': experience})


# 提交经验分享视图
@login_required
def submit_experience(request):
    if request.method == 'POST':
        form = ExperienceForm(request.POST)
        if form.is_valid():
            experience = form.save(commit=False)
            experience.author = request.user
            experience.save()
            messages.success(request, '感谢你的分享，经验提交成功，待审核后将展示给大家。')
            return redirect('experience_list')
        else:
            messages.error(request, '经验分享提交出现问题，请检查填写内容后重新提交。')
    else:
        form = ExperienceForm()
    return render(request, 'experiences/submit_experience.html', {'form': form})